﻿using ProjectManager.Controller;
using ProjectManager.Logic.Content;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectManager.Interface;
using Braincase.GanttChart;

namespace ProjectManager.MainFormTools
{
    internal class UIEventHandler
    {
        #region 内部字段
        private UIContextMenuStrip projectContextMenu;
        private UIContextMenuStrip taskContextMenu1;
        private UIContextMenuStrip membersContextMenu;
        private ILogic logicController;
        private IUser userController;
        private UIListBox subTeams;
        private UITreeView taskTreeView;
        private UIListBox memberListBox;
        private ListView messageListBox;
        private Chart ganttChart;
        private UISmoothLabel nickNameLabel;
        private UIComboBox selectingTeamCB1;
        private UIComboBox selectingTeamCB2;
        #endregion
        public UIEventHandler(UIListBox subTeams, UITreeView taskTreeView, ILogic logicController, IUser userController, UIListBox memberListBox, ListView messageListBox,Chart ganttChart, UISmoothLabel nickNameLabel, UIComboBox selectingTeamCB1, UIComboBox selectingTeamCB2)
        {
      
            // 初始化UIContextMenuStrip
            projectContextMenu = new UIContextMenuStrip();

            taskContextMenu1 = new UIContextMenuStrip();
            taskContextMenu1.Items.Add("新建子任务", null, Menu1Item1_Click);
            taskContextMenu1.Items.Add("提交任务", null, Menu1Item2_Click);
            taskContextMenu1.Items.Add("修改任务", null, Menu1Item3_Click);
            taskContextMenu1.Items.Add("终止/继续", null, Menu1Item4_Click);
            taskContextMenu1.Items.Add("审核任务", null, Menu1Item5_Click);
            membersContextMenu = new UIContextMenuStrip();
            membersContextMenu.Items.Add("删除成员", null, RemoveMemberBtn_Click);

            this.subTeams = subTeams;
            this.taskTreeView = taskTreeView;
            this.logicController = logicController;
            this.userController = userController;
            this.memberListBox = memberListBox;
            this.messageListBox = messageListBox;
            this.ganttChart = ganttChart;
            this.nickNameLabel = nickNameLabel;
            this.selectingTeamCB1 = selectingTeamCB1;
            this.selectingTeamCB2 = selectingTeamCB2;

            ProjectContextMenuUpdate();
           
        }


        #region 项目
        public void ProjectContextMenuUpdate()
        {
            projectContextMenu.Items.Clear();
            projectContextMenu.Items.Add("新建", null, CreateProjectBtn_Click);
            projectContextMenu.Items.Add("加入", null, JoinProjectBtn_Click);
            projectContextMenu.Items.Add("退出当前", null, QuitProjectBtn_Click);
            projectContextMenu.Items.Add(new ToolStripSeparator());
            foreach (var item in logicController.GetProjectList())
            {
                ToolStripMenuItem menuItem = new ToolStripMenuItem(item.Item1.Name);
                menuItem.Tag = item;
                menuItem.Click += OneProjectIsClicked;
                projectContextMenu.Items.Add(menuItem);
            }
        }

        private void OneProjectIsClicked(object sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem menuItem)
            {
                var projectMemberTuple = ((ProjectInformation, MemberInformation))menuItem.Tag;
                logicController.CurrentProject = projectMemberTuple.Item1;
                logicController.CurrentIdentity = projectMemberTuple.Item2;

                // 更新UI
                selectingTeamCB1.Enabled = true;
                selectingTeamCB2.Enabled = true;
                nickNameLabel.Text = logicController.CurrentIdentity.Name;
                UpdateTeamList();
                TaskTreeViewUpdate();
                MessageListBoxUpdate();
            }
        }

        //项目
        public void ProjectBtn_Click(object sender, EventArgs e)
        {
            if (sender is UIHeaderButton button)
            {
                ProjectContextMenuUpdate();
                // 显示左键菜单
                projectContextMenu.Show(button, button.PointToClient(Cursor.Position));
                //********************************************************************************************************************//
                //如何获得所有项目的列表？
                //********************************************************************************************************************

                //
            }
        }


        private void CreateProjectBtn_Click(object sender, EventArgs e)
        {
            userController.GetInput("创建项目", new List<string> { "项目地址", "昵称", "Git账号", "Git密码" }, new List<Type> { typeof(string), typeof(string), typeof(string), typeof(string) }, out List<object> createProjectInputs);
            if (userController.GetInputValid())
            {
                logicController.CreateProject((string)createProjectInputs[0], (string)createProjectInputs[1], (string)createProjectInputs[2], (string)createProjectInputs[3]);

                TaskTreeViewUpdate();
                MessageListBoxUpdate();
            }
        }

        private void JoinProjectBtn_Click(object sender, EventArgs e)
        {
            userController.GetInput("加入项目", new List<string> { "项目地址", "昵称", "Git账号", "Git密码" }, new List<Type> { typeof(string), typeof(string), typeof(string), typeof(string) }, out List<object> addProjectInputs);
            if (userController.GetInputValid())
            {
                logicController.JoinProject((string)addProjectInputs[0], (string)addProjectInputs[1], (string)addProjectInputs[2], (string)addProjectInputs[3]);

                TaskTreeViewUpdate();
                MessageListBoxUpdate();
            }
        }

        private void QuitProjectBtn_Click(object sender, EventArgs e)
        {
            nickNameLabel.Text = "未打开项目";
            selectingTeamCB1.DataSource = null;
            selectingTeamCB2.DataSource = null;
            subTeams.DataSource = null;
            taskTreeView.Nodes.Clear();
            messageListBox.Items.Clear();
            memberListBox.Items.Clear();
            selectingTeamCB1.Enabled = false;
            selectingTeamCB2.Enabled = false;
            
        }

        #endregion


        #region 任务
        private void Menu1Item1_Click(object sender, EventArgs e)
        {
            userController.GetInput("新建子任务", new List<string> { "任务名称", "任务团队","任务描述", "开始时间", "截止时间", "可修改文件路径" }, new List<Type> { typeof(string), typeof(TeamInformation),typeof(string), typeof(DateTime), typeof(DateTime), typeof(List<string>) }, out List<object> createTaskInputs);
            if (userController.GetInputValid())
                logicController.PublishTask((ProjectTaskInformation)taskContextMenu1.Tag, (TeamInformation)createTaskInputs[1], (DateTime)createTaskInputs[3], (DateTime)createTaskInputs[4], (string)createTaskInputs[0], (string)createTaskInputs[2], (List<string>)createTaskInputs[5]);
            TaskTreeViewUpdate();
        }

        private void Menu1Item2_Click(object sender, EventArgs e)
        {
            foreach (var item in ((ProjectTaskInformation)taskContextMenu1.Tag).ChildTask)
            {
                if (item.Status != ProjectTaskStatus.Succeeded)
                {
                    userController.ShowMessage("有子任务未完成，无法提交");
                    return;
                }
            }
            userController.GetInput("提交任务", new List<string> { "提交标题", "提交描述" }, new List<Type> { typeof(string), typeof(string) }, out List<object> submitTaskInputs);
            if(userController.GetInputValid())
                logicController.SubmitTask((ProjectTaskInformation)taskContextMenu1.Tag, (string)submitTaskInputs[0], (string)submitTaskInputs[1]);
            TaskTreeViewUpdate();
        }

        private void Menu1Item3_Click(object sender, EventArgs e)
        {
            
            userController.GetInput("修改任务", new List<string> { "任务名称", "任务团队","任务描述", "开始时间", "截止时间", "任务状态", "可修改文件路径" }, new List<Type> { typeof(string),typeof(TeamInformation), typeof(string), typeof(DateTime), typeof(DateTime), typeof(ProjectTaskStatus), typeof(List<string>) }, out List<object> editTaskInputs);
            if(userController.GetInputValid())
                logicController.UpdateTask((ProjectTaskInformation)taskContextMenu1.Tag, (TeamInformation)editTaskInputs[1], (DateTime)editTaskInputs[3], (DateTime)editTaskInputs[4], (string)editTaskInputs[0], (string)editTaskInputs[2], (List<string>)editTaskInputs[6], (ProjectTaskStatus)editTaskInputs[5]);
            TaskTreeViewUpdate();
        }

       
        private void Menu1Item4_Click(object sender, EventArgs e)
        {
            TeamInformation teamOfCurrentTask = new TeamInformation();
            foreach (var item in logicController.GetTeams())
            {
                if (item.ID==((ProjectTaskInformation)taskContextMenu1.Tag).TeamID)
                {
                    teamOfCurrentTask = item;
                    break;
                }
            }
            if (((ProjectTaskInformation)taskContextMenu1.Tag).Status == ProjectTaskStatus.Stopped)
            {
                logicController.UpdateTask((ProjectTaskInformation)taskContextMenu1.Tag, teamOfCurrentTask, ((ProjectTaskInformation)taskContextMenu1.Tag).StartDate, ((ProjectTaskInformation)taskContextMenu1.Tag).EndDate, ((ProjectTaskInformation)taskContextMenu1.Tag).Name, ((ProjectTaskInformation)taskContextMenu1.Tag).Description, ((ProjectTaskInformation)taskContextMenu1.Tag).protectedPaths, ProjectTaskStatus.Working);
            }
            else if (((ProjectTaskInformation)taskContextMenu1.Tag).Status == ProjectTaskStatus.Working)
            {
                logicController.UpdateTask((ProjectTaskInformation)taskContextMenu1.Tag, teamOfCurrentTask, ((ProjectTaskInformation)taskContextMenu1.Tag).StartDate, ((ProjectTaskInformation)taskContextMenu1.Tag).EndDate, ((ProjectTaskInformation)taskContextMenu1.Tag).Name, ((ProjectTaskInformation)taskContextMenu1.Tag).Description, ((ProjectTaskInformation)taskContextMenu1.Tag).protectedPaths, ProjectTaskStatus.Stopped);
            }
        }

        private void Menu1Item5_Click(object sender, EventArgs e)
        {
            logicController.AuditTaskStart((ProjectTaskInformation)taskContextMenu1.Tag, out List<string> beforePaths, out List<string> completePaths);
            userController.GetInput("审核任务", new List<string> { "审核标题", "审核描述", "是否通过审核" }, new List<Type> { typeof(string), typeof(string), typeof(bool) }, out List<object> auditTaskInputs);
            if(userController.GetInputValid())
                logicController.AuditTaskFinish((ProjectTaskInformation)taskContextMenu1.Tag, (bool)auditTaskInputs[2], (string)auditTaskInputs[0], (string)auditTaskInputs[1]);
            TaskTreeViewUpdate();
        }

        public void TaskTreeViewUpdate()
        {
            taskTreeView.Nodes.Clear();
            if (logicController.GetTasks() != null)
            {
                foreach (var item in logicController.GetTasks())
                {
                    TreeNode node = new TreeNode();
                    node.Tag = item;
                    node.Text = item.Name + "          " + item.Status.ToString();
                    taskTreeView.Nodes.Add(node);
                    foreach (var subItem in item.ChildTask)
                    {
                        TreeNode subNode = new TreeNode();
                        subNode.Tag = subItem;
                        subNode.Text = subItem.Name + "          " + subItem.Status.ToString();
                        node.Nodes.Add(subNode);
                    }
                }
            }
        }
        public void TaskTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                // 显示右键菜单
                taskContextMenu1.Tag = e.Node.Tag;
                if (((ProjectTaskInformation)e.Node.Tag).Status == ProjectTaskStatus.Stopped)
                {
                    taskContextMenu1.Items[3].Enabled = true;
                    taskContextMenu1.Items[3].Text = "继续";
                }
                else if (((ProjectTaskInformation)e.Node.Tag).Status == ProjectTaskStatus.Working)
                {
                    taskContextMenu1.Items[3].Enabled = true;
                    taskContextMenu1.Items[3].Text = "终止";
                }
                else
                {
                    taskContextMenu1.Items[3].Enabled = false;
                }

                TeamInformation teamOfCurrentTask = new TeamInformation();
                foreach (var item in logicController.GetTeams())
                {
                    if (item.ID == ((ProjectTaskInformation)e.Node.Tag).TeamID)
                    {
                        teamOfCurrentTask = item;
                        break;
                    }
                }
                if (teamOfCurrentTask.Leader.ID == logicController.CurrentIdentity.ID)
                {
                    taskContextMenu1.Items[0].Enabled = true;
                    taskContextMenu1.Items[1].Enabled = true;
                    taskContextMenu1.Items[2].Enabled = true;
                    taskContextMenu1.Items[4].Enabled = true;
                }
                else
                {
                    taskContextMenu1.Items[0].Enabled = false;
                    taskContextMenu1.Items[1].Enabled = false;
                    taskContextMenu1.Items[2].Enabled = false;
                    taskContextMenu1.Items[3].Enabled = false;
                    taskContextMenu1.Items[4].Enabled = false;
                }
                taskContextMenu1.Show(taskTreeView, e.Location);
                //********************************************************************************************************************//
                //如何判断某个任务所属的团队，从而确定其主管？
                //主管和任务发布人似乎是同一个人？
                //此处假设所有右键菜单均显示
                //********************************************************************************************************************
            }
        }
        #endregion



        #region 团队
        //更新选项，保持数据绑定

        public void UpdateTeamList()
        {
            selectingTeamCB1.DataSource = logicController.GetTeams();
            selectingTeamCB1.DisplayMember = "Name";
            selectingTeamCB2.DataSource = logicController.GetTeams();
            selectingTeamCB2.DisplayMember = "Name";
        }

        public void SelectingTeamCB1_DropDown(object sender, EventArgs e)
        {
            UpdateTeamList();
        }

        public void SelectingTeamCB1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((UIComboBox)sender).SelectedIndex != -1)
            {
                TeamInformation team = (TeamInformation)((UIComboBox)sender).SelectedItem;
                if (team.IsIndividual || team.Members == null)
                {
                    subTeams.DataSource = null;
                }
                else
                {
                    subTeams.DataSource = team.Members.ToList();
                    subTeams.DisplayMember = "Name";
                }
                
                var project=new ProjectManager<Braincase.GanttChart.Task,object>();
                List<DateTime>dates = new List<DateTime>();
                foreach (var item in team.Tasks)
                {
                    dates.Add(item.StartDate);
                }
                if(dates.Count == 0)
                {
                    return;
                }
                project.Start = dates.Min();
                foreach (var item in team.Tasks)
                {
                    var task = new Braincase.GanttChart.Task();
                    task.Name = item.Name;
                    task.Start = item.StartDate- project.Start;
                    task.End = item.EndDate - project.Start;
                    task.Duration = item.EndDate - item.StartDate;
                    project.Add(task);
                }
               

                // 将项目绑定到 Chart 控件
                ganttChart.Init(project);
            }
        }

        public void SelectingTeamCB2_DropDown(object sender, EventArgs e)
        {
            UpdateTeamList();
        }

        
        public void SelectingTeamCB2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((UIComboBox)sender).SelectedIndex != -1)
            {
               UpdateMemberList();

            }
        }
        public void UpdateMemberList()
        {
            
                // memberListBox.Items.Clear();
                TeamInformation team = (TeamInformation)selectingTeamCB2.SelectedItem;
                if (team.IsIndividual || team.Members == null)
                {
                    memberListBox.DataSource = null;
                }
                else
                {
                    memberListBox.DataSource = team.Members.ToList();
                    memberListBox.DisplayMember = "Name";
                }

        }

        //public void GetMembers(TeamInformation rootTeam, int leaderID)
        //{
        //    membersStored.Add(rootTeam);
        //    if (rootTeam.IsIndividual)
        //    {
        //        if (rootTeam.ID != leaderID)
        //        {
        //            memberListBox.Items.Add(rootTeam.Leader.Name + "            成员");
        //            membersStored.Add(rootTeam);
        //        }
        //        else
        //        {
        //            memberListBox.Items.Add(rootTeam.Leader.Name + "            主管");
        //            membersStored.Add(rootTeam);
        //        }
        //        return;
        //    }
        //    foreach (var item in rootTeam.Members)
        //    {
        //        GetMembers(item, leaderID);
        //    }
        //    return;
        //}

        public void MemberListBox_MouseDown(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Right)
            {
                int index = memberListBox.IndexFromPoint(e.Location);
                if (index != -1)
                {

                    memberListBox.SelectedIndex = index;
                    membersContextMenu.Tag = memberListBox.Items[index];
                    membersContextMenu.Show(memberListBox, e.Location);
                }
            }
        }



        public void CreateTeamBtn_Click(object sender, EventArgs e)
        {
            userController.GetInput("创建团队", new List<string> { "团队名称", "是否为个人团队" }, new List<Type> { typeof(string), typeof(bool) }, out List<object> createTeamInputs);
            if(userController.GetInputValid())
                logicController.CreateTeam((string)createTeamInputs[0], (bool)createTeamInputs[1]);
            UpdateTeamList();
        }

        public void AddMemberBtn_Click(object sender, EventArgs e)
        {
            if (((TeamInformation)(selectingTeamCB2.SelectedItem)).Leader.ID != logicController.CurrentIdentity.ID)
            {
                userController.ShowMessage("您不是团队负责人，无法添加成员");
                return;
            }
            userController.GetInput("添加成员", new List<string> { "成员团队" }, new List<Type> { typeof(TeamInformation) }, out List<object> addMemberInputs);
            if(userController.GetInputValid())
                logicController.TeamAddMember((TeamInformation)selectingTeamCB2.SelectedItem, (TeamInformation)addMemberInputs[0]);
            UpdateMemberList();
        }

        public void DisbandTeamBtn_Click(object sender, EventArgs e)
        {
            if (((TeamInformation)(selectingTeamCB2.SelectedItem)).Leader.ID != logicController.CurrentIdentity.ID)
            {
                userController.ShowMessage("您不是团队负责人，无法添加成员");
                return;
            }
            else
            {
                DialogResult result = MessageBox.Show("确认解散吗？", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

                // 根据用户的选择执行相应的操作
                if (result == DialogResult.OK)
                {
                    logicController.DisbandTeam(((TeamInformation)(selectingTeamCB2.SelectedItem)));
                    UpdateTeamList();
                    MessageBox.Show("已解散", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (result == DialogResult.Cancel)
                {
                    MessageBox.Show("已取消", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }



        public void RemoveMemberBtn_Click(object sender, EventArgs e)
        {
            if (((TeamInformation)(selectingTeamCB2.SelectedItem)).Leader.ID != logicController.CurrentIdentity.ID)
            {
                userController.ShowMessage("您不是团队负责人，无法删除成员");
            }
            else if (((TeamInformation)(selectingTeamCB2.SelectedItem)).Leader.ID==((TeamInformation)(membersContextMenu.Tag)).Leader.ID)
            {
                userController.ShowMessage("无法删除团队主管");
            }
            else
            {
                DialogResult result = MessageBox.Show("确认删除吗？", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                // 根据用户的选择执行相应的操作
                if (result == DialogResult.OK)
                {
                    logicController.TeamRemoveMember((TeamInformation)selectingTeamCB2.SelectedItem, (TeamInformation)membersContextMenu.Tag);
                    UpdateMemberList();
                    MessageBox.Show("已删除", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (result == DialogResult.Cancel)
                {
                    MessageBox.Show("已取消", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        #endregion

        #region 消息

        List<string> messagesRead = new List<string>();
        public void MessageListBoxUpdate()
        {

            messageListBox.Items.Clear();
            foreach (var item in logicController.CheckMessages())
            {
                if(!messagesRead.Contains(item))
                {
                    messageListBox.Items.Add(new ListViewItem(new[] {item,"未读"}));
                }
            }
            foreach (var item in logicController.CheckMessages())
            {
                if(messagesRead.Contains(item))
                {
                    messageListBox.Items.Add(new ListViewItem(new[] { item, "" }));
                }
            }
        }

        public void MessageListBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (((ListView)sender).SelectedItems.Count > 0)
            {
                ListViewItem selectedItem = ((ListView)sender).SelectedItems[0];
                userController.ShowMessage(selectedItem.Text);
                if(!messagesRead.Contains(selectedItem.Text))
                    messagesRead.Add(selectedItem.Text);
                MessageListBoxUpdate();
            }
        }
        #endregion
    }
}
